options(stringsAsFactors = FALSE)

library(readstata13)
library(tidyverse)

r <- data.frame(read.dta13("reasons_by_comment.dta"))
r <- group_by(r, position, reason) %>% 
    summarize(n=n()) %>% 
    mutate(p = factor(position, levels=c("support", "neutral", "oppose"))) %>%
    group_by(p) %>% 
    mutate(rpct = n/sum(n)) %>%
    mutate(reason = factor(reason, levels=sort(unique(r$reason), decreasing=TRUE)))


ggplot(data=r, aes(reason, rpct)) + 
    geom_col(aes(fill=p), position="dodge") + 
    coord_flip() + 
    facet_wrap(~p) +
    scale_fill_manual("p", values = c("support" = "grey60", "neutral" = "grey40", "oppose" = "grey20")) +
    xlab("") + ylab("% of Group Naming Reason") +
    scale_y_continuous(labels = scales::percent) +
    theme_minimal(base_size=12)+
    theme(legend.position = "none") +
    theme(panel.spacing.x=unit(1, "lines"), panel.spacing.y=unit(1, "lines"))
ggsave(file="../Paper/tables/figure3.pdf", width=6.5, height=8, units="in")


r <- data.frame(read.dta13("town_40b_support_comments.dta")) %>% na.omit()

ggplot(data=r, aes(x=housing_support)) + 
    geom_histogram(binwidth=.05) +
    scale_x_continuous(labels = scales::percent, limits=c(0,1), breaks=seq(0,1,.1), minor_breaks = NULL) +
    ylab("Towns") +
    xlab("Vote for Affordable Housing in 40B Referendum") +
    theme_minimal(base_size = 12)
ggsave(file="../Paper/tables/figure1.pdf", width=6, height=3, units="in")
    
ggplot(data=filter(r, n_comments>=10), aes(x=housing_support, y=pct_sup)) +
    geom_abline(intercept=0, slope=1, col="grey25", lty=2)+
    #geom_vline(xintercept=.5, col="red", lty=2)+
    geom_point() +
    scale_x_continuous(labels = scales::percent, limits=c(0,1), breaks=seq(0,1,.1), minor_breaks = NULL) +
    scale_y_continuous(labels = scales::percent, limits=c(0,1), breaks=seq(0,1,.1), minor_breaks = NULL) +
    theme_minimal(base_size = 12) +
    xlab("Vote for Affordable Housing in 40B Referendum") +
    ylab("% Comments Supporting\nMultifamily Housing Developments")
ggsave(file="../Paper/tables/figure2.pdf", width=5, height=4, units="in")
